package com.example.concurrentprogramming8016.ReentrantReadWriteLock;

import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author liyanhao
 * @Date 2023-01-07 16:42
 * ReentrantReadWriteLock官方实例
 * ReentrantReadWriteLocks 可用于在某些类型的集合的某些使用中提高并发性。
 * 通常，仅当集合预计很大、由比编写器线程更多的读取器线程访问，
 * 并且需要开销超过同步开销的操作时，这才值得。
 * 例如，下面是一个使用树状图的类，该类应很大且可同时访问。
 */
public class RWDictionary {
    private final TreeMap<String, Data> treeMap = new TreeMap<String, Data>();
    private final ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    private Lock rlock = reentrantReadWriteLock.readLock();
    private Lock wLock = reentrantReadWriteLock.writeLock();

    public Data getData(String key) {
        rlock.lock();
        try {
            return treeMap.get(key);
        } finally {
            rlock.unlock();
        }
    }

    private Set<String> getAllKeys() {
        rlock.lock();
        try {
            return treeMap.keySet();
        } finally {
            rlock.unlock();
        }
    }

    public Data put(String key, Data data) {
        wLock.lock();
        try {
            return treeMap.put(key, data);
        } finally {
            wLock.unlock();
        }
    }

    public void clear() {
        wLock.lock();
        try {
            treeMap.clear();
        } finally {
            wLock.unlock();
        }
    }


}

class Data {

}
